package com.springboot.middleware.server.service;

import com.google.common.base.Strings;
import com.springboot.middleware.model.entity.Item;
import com.springboot.middleware.model.mapper.ItemMapper;
import com.springboot.middleware.server.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CachePassService {
    private static final Logger log = LoggerFactory.getLogger(CachePassService.class);
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private RedisUtils redisUtils;

    //定义缓存中key命名的前缀
    private static final String keyPrefix = "item:";

    /**
    * 根据item的code获取对应的Item
    *   如果在Redis里,从Redis里获取;如果不在Redis里,从数据库里获取,同时加入Redis里.
    *   防止缓存穿透,当数据库也不存在时,依然给Redis里放一个数据,key:value = (keyPrefix+itemCode):""
    * @param itemCode item.Code
    * @return item对象
    * */
    public Item getItemInfo(String itemCode) {
        Item item = null;
        //缓存中真正的Key有前缀和商品编码组成
        final String key = keyPrefix + itemCode;
        if(redisUtils.hasKey(key)) {
            log.info("---获取商品详情-缓存中存在该商品---商品编号为:{}",itemCode);
            //获取该value
            Item value = (Item) redisUtils.get(key);
            if (value != null && !Strings.isNullOrEmpty(value.toString())) {
                item = value;
            }
        } else {
            log.info("---获取商品详情-缓存中不存在该商品-从数据库中查询---商品编号为:{}",itemCode);
            item = itemMapper.selectByCode(itemCode);
            if (item != null) {
                redisUtils.set(key, item);
            } else {
                redisUtils.set(key,"", 30*60);//过期失效时间
            }
        }
        return item;
    }
}
